/**
 * 封装 axios 请求模块
 */
import axios from 'axios'
import store from '@/store/index.js'
import JSONbig from 'json-bigint'
import router from '@/router'
import { Toast } from 'vant'
// import { refreshToken } from '@/api/user.js'

const request = axios.create({
  baseURL: 'http://ttapi.research.itcast.cn', // 基础路径
  // baseURL: 'https://toutiao.m.lipengzhou.com', // 基础路径
  transformResponse: [function (data) {
    try {
      return JSONbig.parse(data)
    } catch (e) {
      return data
    }
  }]
})

// 请求拦截器
request.interceptors.request.use(function (config) {
  const user = store.state.user.user
  // if (user) {
  //   const currentTimestamp = Date.parse(new Date())
  //   console.log(currentTimestamp)
  //   console.log(user.expire_at)
  //   console.log(user.expire_at - currentTimestamp)
  //   const remainTime = user.expire_at - currentTimestamp
  //   if (remainTime >= 7200000 || remainTime <= 0) { // token过期
  //     const promiseFresh = new Promise((resolve, reject) => {
  //       refreshToken().then(res => { // 刷新token
  //         config.headers.Authorization = `Bearer ${res.data.data.token}`
  //         store.commit('user/refreshToken') // 更新store
  //         resolve(config)
  //       })
  //     })
  //     return promiseFresh
  //   } else {
  //     config.headers.Authorization = `Bearer ${user.token}`
  //   }
  // }
  if (user) {
    config.headers.Authorization = `Bearer ${user.token}`
  }
  return config
}, function (error) {
  return Promise.reject(error)
})

// 响应拦截器
axios.interceptors.response.use(function (response) {
  return response
}, function (error) {
  const status = error.response.status
  if (error.response && (status === 401 || status === 403)) {
    store.commit('user/deleteUser')
    router.push('/login')
    Toast.fail('登录状态无效，请重新登录')
  } else if (status === 400) {
    Toast.fail('请求参数错误')
  } else if (status > 500) {
    Toast.fail('服务端内部异常，请稍后重试')
  }
  return Promise.reject(error)
})

export default request
